package com.baor.service.impl;

import com.baor.dao.DeliveryRecordDao;
import com.baor.dao.EquipmentDao;
import com.baor.domain.DeliveryRecordVO;
import com.baor.domain.Equipment;
import com.baor.domain.EquipmentVO;
import com.baor.service.DeliveryRecordService2;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DeliveryRecordServiceImpl2 implements DeliveryRecordService2 {


    @Autowired
    private DeliveryRecordDao deliveryRecordDao;
    @Autowired
    private EquipmentDao equipmentDao;

    @Override
    public R DeliveryRecord2(Map<String, Object> params) {
        try {
            // 构建查询条件（无需分页参数）
            MPJLambdaWrapper<DeliveryRecordVO> wrapper = new MPJLambdaWrapper<>(DeliveryRecordVO.class)
                    .select(DeliveryRecordVO::getId,
                            DeliveryRecordVO::getDeliveryTime,
                            DeliveryRecordVO::getWeight)
                    .select(EquipmentVO::getAddress)
                    .leftJoin(EquipmentVO.class, EquipmentVO::getId, DeliveryRecordVO::getEquipmentId)
                    .orderByDesc(DeliveryRecordVO::getDeliveryTime);

            // 执行全量查询（不分页）
            List<Map<String, Object>> records = deliveryRecordDao.selectJoinMaps(wrapper);

            // 转换数据格式为前端所需
            List<Map<String, Object>> resultList = records.stream()
                    .map(this::convertToFrontendFormat)
                    .collect(Collectors.toList());

            // 封装返回结果（不含分页信息）
            Map<String, Object> result = new HashMap<>();
            result.put("list", resultList);
            result.put("totalSize", resultList.size()); // 总条数为查询结果数

            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询失败：" + e.getMessage());
        }
    }

    /**
     * 转换数据库字段为前端展示格式
     */
    private Map<String, Object> convertToFrontendFormat(Map<String, Object> record) {
        Map<String, Object> item = new HashMap<>();
        item.put("recordId", record.get("id"));           // 记录ID
        item.put("deliveryTime", record.get("delivery_time")); // 投递时间
        item.put("weight", record.get("weight"));         // 投递重量
        item.put("deviceAddress", record.get("address")); // 设备地址
        return item;
    }


    /**
     *     序启回收--投递记录
     */
    @Override
    public R DeliveryRecord(@RequestBody Map<String,Object> params) {

        System.out.println("用户id:"+params.get("userId"));
        try {
            // 构建查询条件（无需分页参数）
            MPJLambdaWrapper<DeliveryRecordVO> wrapper = new MPJLambdaWrapper<>(DeliveryRecordVO.class)
                    .select(DeliveryRecordVO::getId,
                            DeliveryRecordVO::getDeliveryTime,
                            DeliveryRecordVO::getWeight,
                            DeliveryRecordVO::getCategory,
                            DeliveryRecordVO::getIntegral,
                            DeliveryRecordVO::getDeductIntegral
                            )
                    .eq(DeliveryRecordVO::getUserId, params.get("userId"))
                    .select(EquipmentVO::getAddress)
                    .leftJoin(EquipmentVO.class, EquipmentVO::getId, DeliveryRecordVO::getEquipmentId)
                    .orderByDesc(DeliveryRecordVO::getDeliveryTime);

            // 执行全量查询（不分页）
            List<Map<String, Object>> records = deliveryRecordDao.selectJoinMaps(wrapper);

            // 转换数据格式为前端所需
            List<Map<String, Object>> resultList = records.stream()
                    .map(this::convertToFrontendFormat2)
                    .collect(Collectors.toList());

            // 封装返回结果（不含分页信息）
            Map<String, Object> result = new HashMap<>();
            result.put("list", resultList);
            result.put("totalSize", resultList.size()); // 总条数为查询结果数

            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询失败：" + e.getMessage());
        }
    }

    private Map<String, Object> convertToFrontendFormat2(Map<String, Object> record) {
        Map<String, Object> item = new HashMap<>();
        item.put("recordId", record.get("id"));           // 记录ID
        item.put("deliveryTime", record.get("delivery_time")); // 投递时间
        item.put("weight", record.get("weight"));         // 投递重量
        item.put("deviceAddress", record.get("address")); // 设备地址
        item.put("category", record.get("category"));
        item.put("integral", record.get("integral"));
        item.put("deduct_integral", record.get("deduct_integral"));
        item.put("code", record.get("code"));
        return item;
    }

    @Override
    public R DeliveryMap(Map<String, Object> params) {
        MPJLambdaWrapper<Equipment> wrapper = new MPJLambdaWrapper<>(Equipment.class);
        wrapper.select(Equipment::getAddress,
                       Equipment::getCode,
                       Equipment::getLongitude,
                       Equipment::getLatitude,
                       Equipment::getStatus,
                       Equipment::getStorageStatus,
                       Equipment::getIsStatus
                );
        List<Map<String, Object>> records = equipmentDao.selectJoinMaps(wrapper);
        List<Map<String, Object>> resultList = records.stream()
                .map(this::convertToFrontendFormat3)
                .collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("list", resultList);
        result.put("totalSize", resultList.size()); // 总条数为查询结果数

        return R.ok(result);
    }
    private Map<String, Object> convertToFrontendFormat3(Map<String, Object> record) {
        Map<String, Object> item = new HashMap<>();
        item.put("code", record.get("code"));
        item.put("status", record.get("status"));
        item.put("storage_status", record.get("storage_status"));
        item.put("is_status", record.get("is_status"));
        item.put("address", record.get("address"));
        item.put("longitude", record.get("longitude"));
        item.put("latitude", record.get("latitude"));
        return item;
    }
}